package me.leiusual.sharing.ui.shop

import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.viewModels
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import dagger.android.support.DaggerFragment
import kotlinx.android.synthetic.main.fragment_shop_withdraw.*
import me.leiusual.sharing.R
import me.leiusual.sharing.api.model.Withdraw
import me.leiusual.sharing.repository.model.Data
import me.leiusual.sharing.ui.helper.HandleObserver
import me.leiusual.sharing.ui.helper.ItemTouchHelperCallbackImpl
import me.leiusual.sharing.ui.shop.adapter.ShopWithdrawAdapter
import me.leiusual.sharing.ui.shop.adapter.ShopWithdrawViewHolder
import me.leiusual.sharing.util.extension.requireValue
import me.leiusual.sharing.util.extension.toast
import timber.log.Timber
import javax.inject.Inject

/**
 * author: leiusual
 * create on: 2019-07-31
 * description:
 */
class ShopWithdrawFragment : DaggerFragment(), View.OnClickListener {

  @Inject
  lateinit var factory: ViewModelProvider.Factory

  private val viewModel: ShopWithdrawViewModel by viewModels { factory }

  override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    return inflater.inflate(R.layout.fragment_shop_withdraw, container, false)
  }

  override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    toolbar.setNavigationOnClickListener {
      findNavController().popBackStack()
    }

    recycler_view.adapter = ShopWithdrawAdapter({

      Timber.v("申请：%s", it)
      viewModel.withdrawApply(it.id)
    }, {

      Timber.v("撤回：%s", it)
      viewModel.withdrawCancel(it.id)
    })
    ItemTouchHelper(object : ItemTouchHelperCallbackImpl() {

      override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
        Timber.v("删除")

        // 删除
        val shopWithdrawViewHolder = viewHolder as ShopWithdrawViewHolder
        val withdraw = shopWithdrawViewHolder.withdraw

        when (withdraw.auditStatus) {
          Withdraw.AuditStatus.NOT_APPLY -> {

            // 允许用户删除
            viewModel.withdrawDelete(withdraw.id)
          }
          else -> {

            // 不允许用户操作
            toast("不允许删除")
            recycler_view.adapter?.notifyDataSetChanged()
          }
        }
      }
    }).attachToRecyclerView(recycler_view)

    button_new_withdraw.setOnClickListener(this)

    observeData()
    viewModel.withdrawQuery(viewModel.store.currentStoreId, true)
  }

  override fun onClick(v: View?) {
    when (v?.id) {
      R.id.button_new_withdraw -> {
        findNavController().navigate(R.id.action_shopWithdrawFragment_to_shopWithdrawEditFragment)
      }
    }
  }

  private fun observeData() {
    viewModel.loadInitial.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("loadInitial = %s", it)
      when (it) {
        is Data.Loading -> {
          if (viewModel.withdrawQueryParams.requireValue.first) {
            state_constraint_layout.showProgress()
          }
        }
        is Data.Error -> {
          state_constraint_layout.showError(it.error.message)
        }
        is Data.Success -> {
          state_constraint_layout.showContent()
        }
      }
    })

    viewModel.withdrawQuery.observe(viewLifecycleOwner, Observer {
      Timber.v("withdrawQuery = %s", it)

      if (it.isEmpty()) {
        state_constraint_layout.showEmpty()
      } else {
        state_constraint_layout.showContent()

        val adapter = recycler_view.adapter as ShopWithdrawAdapter
        adapter.submitList(it)
      }
    })

    viewModel.withdrawApply.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("withdrawApply = %s", it)
      when (it) {
        is Data.Loading -> {
          // ignore
        }
        is Data.Error -> {
          toast(it.error.message)
        }
        is Data.Success -> {
          viewModel.withdrawQuery(viewModel.store.currentStoreId, false)
        }
      }
    })

    viewModel.withdrawCancel.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("withdrawCancel = %s", it)
      when (it) {
        is Data.Loading -> {
          // ignore
        }
        is Data.Error -> {
          toast(it.error.message)
        }
        is Data.Success -> {
          viewModel.withdrawQuery(viewModel.store.currentStoreId, false)
        }
      }
    })

    viewModel.withdrawDelete.observe(viewLifecycleOwner, HandleObserver {
      Timber.v("withdrawDelete = %s", it)
      when (it) {
        is Data.Loading -> {
          // ignore
        }
        is Data.Error -> {
          toast(it.error.message)
          recycler_view.adapter?.notifyDataSetChanged()
        }
        is Data.Success -> {
          viewModel.withdrawQuery(viewModel.store.currentStoreId, false)
        }
      }
    })
  }
}